import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { SettingDrawer, PageLoading } from '@ant-design/pro-layout';
import { getCookie, setCookie } from '@/utils/cookieUtils';
import type { RunTimeLayoutConfig, RequestHandler } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { Button, notification, Space } from 'antd';
import defaultSettings from '../config/defaultSettings';
import { authInfo, putSessionItem } from '@/services/authService'
import { codeMessage } from '@/constants/requestConstant'
import IconFont from './pages/editor/flow/common/IconFont';
import * as signalR from '@microsoft/signalr';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
//const baseUrl = 'http://101.33.254.90:13000';
const baseUrl = 'http://localhost:13000';
//const imgUrl = 'http://101.33.254.90:13000';
const imgUrl = 'http://localhost:13000';

export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: AdminUserType.AdminUserResponse;
  loading?: boolean;
  fetchUserInfo?: () => Promise<AdminUserType.AdminUserResponse | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const { Items } = await authInfo();
      return Items[0].UserEntity;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const getOperate = (status: any) => {
    switch (status) {
      case -2:
        return "取消";
      case 0:
        return "下了";
      default:
        return "";
    }
  }

  const openNotification = (newOrder: any[]) => {
    console.log(newOrder)
    const key = `open${Date.now()}`;
    const btn = (
      <Space>
        <Button type="link" size="small" onClick={() => { history.push("/shop/orderDetail/index/" + newOrder[0].id) }}>
          查看
        </Button>
        <Button type="primary" size="small" onClick={() => { }}>
          关闭
        </Button>
      </Space>
    );


    if ([-2, 0].indexOf(newOrder[0].status) === -1) {
      return;
    }

    notification.open({
      message: '新订单',
      description:
        `用户${newOrder[0].orderUserName}${getOperate(newOrder[0].status)}订单`,
      btn,
      key,
      duration: 10,
      onClose: close,
      placement: 'bottomRight'
    });
  }

  const registerSignalR = () => {
    const connection = new signalR.HubConnectionBuilder().withUrl("http://101.33.254.90:13000/api/userOrderHub").build();
    connection.on("AddNewOrder", function (newOrder) {
      openNotification(newOrder);
    });

    connection.start().then(function () {
    }).catch(function (err) {
      return console.error(err.toString());
    });
  }

  if (history.location.pathname !== loginPath) {
    registerSignalR();
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    menuItemRender: (menuItemProps) => {
      return (
        <Link to={menuItemProps.path ? menuItemProps.path : '#'}>
          {menuItemProps.icon && < IconFont type={menuItemProps.icon.toString()} />}	{menuItemProps.name}
        </Link>
      )
    },
    subMenuItemRender: (subMenuITem) => {
      return (
        <span className="ant-pro-menu-item">
          <span role="img" className="anticon">
            {subMenuITem.icon && <IconFont type={subMenuITem.icon.toString()} />}
          </span>
          <span>
            {subMenuITem.name}
          </span>
        </span>
      )
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.UserName,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
        // <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
        //   <LinkOutlined />
        //   <span>OpenAPI 文档</span>
        // </Link>,
        // <Link to="/~docs" key="docs">
        //   <BookOutlined />
        //   <span>业务组件文档</span>
        // </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    ...initialState?.settings,
  };
};

// 全局请求
const requestInterceptor = (url: any, options: any) => {
  return {
    url: isDev ? baseUrl + url : '',
    options: {
      ...options,
      headers: {
        ...options.headers,
        Authorization: getCookie("token") ? `${getCookie("token")}` : "",
      },
    },
  };
};

// 全局相应拦截
const responseInterceptor = (response: any, options: any) => {
  console.log('返回了');
  const shopId = getCookie("shopId");
  if (shopId) {
    setCookie("shopId", shopId);
  }
  return response;
};

const errorHandler = (error: any) => {
  const { response } = error;
  if (response?.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    console.log(`请求错误 ${status}: ${url}`);
    // notification.error({
    //   message: `请求错误 ${status}: ${url}`,
    //   description: errorText,
    // });
  }

  if (!response) {
    // notification.error({
    //   description: '您的网络发生异常，无法连接服务器',
    //   message: '网络异常',
    // });
  }
  throw error;
};

export const request = {
  baseUrl: baseUrl,
  imgUrl: imgUrl,
  timeout: 10000,
  errorConfig: {},
  middlewares: [],
  // 异常处理
  errorHandler,
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptor],
};

